<template>
  <div class="clearfix">
    <input type="file" id="file" accept="image/*" @change="handleChange" />
  </div>
</template>
<script lang="ts" setup>
import Compressor from "compressorjs";

/**
 * 将blob对象转换为文件
 * @param blob
 * @param fileName
 */
function blobToFile(blob, fileName) {
  // 创建一个新的 File 对象，传入 Blob 对象和文件名
  const options = {
    type: blob.type,
    lastModified: Date.now(),
  };
  return new File([blob], fileName || blob.name, options);
}

/**
 * 将文件转换为blob对象
 * @param file
 */
function fileToBlob(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = () => {
      const blob = new Blob([reader.result], { type: file.type });
      resolve(blob);
    };

    reader.onerror = () => {
      reject(new Error("文件转换为 Blob 时发生错误。"));
    };

    reader.readAsArrayBuffer(file);
  });
}

// 将图片file转换成blob并写入body中
const handleChange = (e) => {
  const file = e.target?.files[0];
  displayImageInBody(file);
  alert(file.size / 1024 / 1024);
  console.log("17:49 file的值：", file);
  if (!file) {
    return;
  }

  new Compressor(file, {
    quality: 0.7,

    // The compression process is asynchronous,
    // which means you have to access the `result` in the `success` hook function.
    success(result) {
      console.log("17:48 压缩后的值：", result);
      const file = blobToFile(result, result.name);
      console.log("18:59 file的值：", file);
      alert(file.size / 1024 / 1024);
      displayImageInBody(file);
      const formData = new FormData();
      // The third parameter is required for server
      formData.append("file", result, result.name);
      console.log("17:47 formDate的值：", formData);
    },
    error(err) {
      console.log(err.message);
    },
  });
};

function displayImageInBody(file) {
  const img = document.createElement("img"); // 创建 <img> 元素

  const reader = new FileReader();

  reader.onload = function () {
    const blob = new Blob([reader.result], { type: file.type }); // 创建 Blob 对象

    img.src = URL.createObjectURL(blob); // 将 Blob 赋给 <img> 的 src 属性
  };

  reader.readAsArrayBuffer(file); // 读取文件并将其转换为 Blob

  document.body.appendChild(img); // 将 <img> 元素插入到 <body> 中
}
</script>
<style scoped>
/deep/ .ant-upload-select-picture-card {
  width: 300px;
  height: 300px;
}
</style>
